package top.superflow.server.config

import com.fasterxml.jackson.annotation.JsonInclude.Include
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.context.annotation.{Bean, Configuration}
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import top.superflow.core.pool.resource.ResourcePoolManager
import top.superflow.core.pool.resource.imp.GlobalResourcePoolManager
import top.superflow.core.pool.{DefaultPoolManagerConfig, PoolManagerConfig}
import top.superflow.flow.load.GlobalFlowConfiguration
import top.superflow.flow.runtime.context.{GlobalContext, ResourceContext}

@Configuration
@EnableAutoConfiguration
@ConfigurationProperties
class ServerConfig {

  @Bean(Array("poolManagerConfig"))
  def getPoolManagerConfig : PoolManagerConfig = {
    new DefaultPoolManagerConfig
  }

  @Bean(Array("globalContext"))
  def getGlobalContext (@Qualifier("globalResourcePoolManager")  resourcePoolManager: ResourcePoolManager): GlobalContext = {
    new GlobalContext with ResourceContext {
      override def getResourcePoolManager: ResourcePoolManager = {
        resourcePoolManager
      }
    }
  }

  @Bean(Array("flowConfiguration"))
  def getFlowConfiguration : GlobalFlowConfiguration = {
    GlobalFlowConfiguration.getInstance
  }

  @Bean(Array("globalResourcePoolManager"))
  def getGlobalResourcePoolManager(@Qualifier("poolManagerConfig")  poolManagerConfig: PoolManagerConfig) : GlobalResourcePoolManager = {
    GlobalResourcePoolManager.init(poolManagerConfig)

    GlobalResourcePoolManager.getInstance
  }


  @Bean def customJackson: Jackson2ObjectMapperBuilderCustomizer = new Jackson2ObjectMapperBuilderCustomizer() {
    override def customize(jacksonObjectMapperBuilder: Jackson2ObjectMapperBuilder): Unit = {
      jacksonObjectMapperBuilder.serializationInclusion(Include.NON_NULL)
      jacksonObjectMapperBuilder.failOnUnknownProperties(false)
      jacksonObjectMapperBuilder.propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE)
      jacksonObjectMapperBuilder.modules(DefaultScalaModule)
    }
  }


}
